LINQ (Language Integrated Query) is one of the most powerful and elegant features in C#. It allows you to query collections, databases, XML, and more — using a SQL-like syntax directly in C#.
What is LINQ?
LINQ stands for Language Integrated Query. It provides a consistent, readable, and type-safe way to query different types of data sources such as:
- Arrays and Lists
- XML Documents
- Databases (via LINQ to SQL or Entity Framework)
- JSON or Web APIs
Benefits of LINQ
| Benefit | Description |
|---|---|
| Unified Query Style | Same syntax for querying different data sources |
| Type Safety | Errors caught at compile-time, not runtime |
| Readability | Code is cleaner and closer to English or SQL |
| Productivity | Reduces the amount of boilerplate looping and filtering code |
LINQ Query Syntax vs Method Syntax
C# offers two ways to write LINQ queries:
1. Query Syntax (SQL-like style)
var result = from n in numbers
where n > 5
orderby n
select n;
2. Method Syntax (Lambda-based)
var result = numbers.Where(n => n > 5).OrderBy(n => n);
Both produce the same result — it’s just a matter of preference!
LINQ with Collections – Example
using System;
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> names = new List<string> { "Alice", "Bob", "Eve", "Charlie" };
// LINQ query to filter names starting with 'C'
var result = from name in names
where name.StartsWith("C")
select name;
foreach (var name in result)
{
Console.WriteLine(name); // Output: Charlie
}
}
}
Common LINQ Operators
| Operator | Description |
|---|---|
Where |
Filters a sequence based on condition |
Select |
Projects each element into a new form |
OrderBy |
Sorts elements in ascending order |
OrderByDescending |
Sorts in descending order |
GroupBy |
Groups elements |
Join |
Joins two sequences based on keys |
Distinct |
Removes duplicates |
Take, Skip |
Limits and skips elements |
Any, All |
Checks for conditions |
LINQ Example with Integers
int[] numbers = { 1, 2, 3, 4, 5, 6 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
foreach (int num in evenNumbers)
{
Console.WriteLine(num); // Output: 2, 4, 6
}
LINQ to Objects vs LINQ to SQL
| Feature | LINQ to Objects | LINQ to SQL/EF |
|---|---|---|
| Source | In-memory collections | Database tables |
| Execution | Immediate or deferred | Translates to SQL queries |
| Libraries Used | System.Linq |
System.Data.Linq, Entity Framework |
Summary
| Topic | Description |
|---|---|
| LINQ Full Form | Language Integrated Query |
| Main Types | Query Syntax, Method Syntax |
| Works With | Arrays, Lists, XML, SQL, JSON |
| Key Benefits | Cleaner code, type-safe, reusable logic |
Next Steps
- Learn deferred execution and how LINQ works under the hood
- Dive into LINQ to SQL or Entity Framework
- Explore GroupBy, Join, and Aggregate functions
Leave Comment